﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Net;
using System.Reflection;

namespace Model
{
    public static class StaticUtil
    {
        #region getvalue
        public static string GetString(object value)
        {
            if (value == null)
                return "";
            if (value is DBNull)
                return "";
            return value.ToString();
        }

        public static string GetString(object value, string valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            if (value is DBNull)
                return valueWhenNull;
            return value.ToString();
        }

        public static bool GetBool(object value)
        {
            return GetBool(value, false);
        }

        public static bool GetBool(object value, bool valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            else
                if (value is DBNull)
                    return valueWhenNull;
                else
                    return (bool)value;
        }

        public static bool GetBool(bool? value)
        {
            return GetBool(value, false);
        }

        public static bool GetBool(bool? value, bool valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            else
                return value.Value;
        }

        public static bool? GetRealBool(object value)
        {
            if (value == null)
                return null;
            else
                if (value is DBNull)
                    return null;
                else
                    return Convert.ToBoolean(value);
        }

        public static int GetInt(object value)
        {
            return GetInt(value, int.MinValue);
        }

        public static int GetInt(object value, int valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            if (value is DBNull)
                return valueWhenNull;

            int i = 0;
            try
            {
                i = Convert.ToInt32(value);
            }
            catch
            {
                return valueWhenNull;
            }
            return i;
        }

        public static int GetInt(int? value)
        {
            return GetInt(value, int.MinValue);
        }

        public static int GetInt(int? value, int valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            else
                return value.Value;
        }

        public static int? GetRealInt(object value)
        {
            return GetRealInt(value, null);
        }

        public static int? GetRealInt(object value, int? valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            if (value is DBNull)
                return valueWhenNull;
            int i = 0;
            try
            {
                i = Convert.ToInt32(value);
            }
            catch
            {
                return null;
            }
            return i;
        }

        public static double GetDouble(double? value)
        {
            return GetDouble(value, double.MinValue);
        }

        public static double GetDouble(object value)
        {
            return GetDouble(value, double.MinValue);
        }

        public static double? GetRealDouble(object value)
        {
            if (value == null)
                return null;
            if (value is DBNull)
                return null;
            return GetDouble(value);
        }

        public static double GetDouble(double? value, double valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            else
                if (double.IsInfinity(value.Value))
                    return valueWhenNull;
                else
                    return value.Value;
        }

        public static double GetDouble(object value, double valueWhenNull)
        {
            double d = valueWhenNull;
            if (value == null)
                return d;
            if (value is DBNull)
                return d;

            System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo();
            format.NumberGroupSeparator = ",";
            format.NumberDecimalSeparator = ".";

            string svalue = value.ToString();
            svalue = svalue.Replace(',', '.');

            try
            {
                d = double.Parse(svalue, format);
            }
            catch
            {
            }

            return d;
        }

        public static DateTime GetDateTime(object value, DateTime valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            if (value is DBNull)
                return valueWhenNull;

            DateTime i = DateTime.MinValue;
            try
            {
                i = Convert.ToDateTime(value);
            }
            catch
            {
                return valueWhenNull;
            }
            return i;
        }

        public static DateTime GetDateTime(object value)
        {
            return GetDateTime(value, DateTime.MinValue);
        }

        public static DateTime GetDateTime(DateTime? value)
        {
            return GetDateTime(value, DateTime.MinValue);
        }

        public static DateTime GetDateTime(DateTime? value, DateTime valueWhenNull)
        {
            if (value == null)
                return valueWhenNull;
            else
                return value.Value;
        }

        public static DateTime? GetRealDateTime(object value)
        {
            if (value == null)
                return null;
            if (value is DBNull)
                return null;
            return Convert.ToDateTime(value);
        }

        public static string GetTextDateTime(DateTime? dt)
        {
            if (dt == null)
                return null;
            else
                return dt.Value.ToString("dd/MM/yyyy");
        }
        #endregion getvalue

        #region other
        public static bool Log_ValidColumn(string name)
        {
            return (name != "STT0" && name != "IsNew" && name != "IsDeleted" && name != "IsDirty" && name != "IsSavable" && name != "IsValid" && name != "BrokenRulesCollection" && name != "USRC" && name != "DATC" && name != "USRM" && name != "DATM" && name != "DELE" && name != "HstOldValue");
        }

        public static Hashtable GetOldData(object obj)
        {
            Hashtable hst = new Hashtable();

            Type t = obj.GetType();
            MemberInfo[] mi = t.GetMembers();
            int length = mi.Length;
            string name = "";
            object objValue = null;
            string strValue = null;

            for (int i = 0; i < length; i++)
                if (mi[i].MemberType == MemberTypes.Property)
                {
                    name = mi[i].Name;
                    if (name != "STT0" && name != "IsNew" && name != "IsDeleted" && name != "IsDirty" && name != "IsSavable" && name != "IsValid" && name != "BrokenRulesCollection" && name != "USRC" && name != "DATC" && name != "USRM" && name != "DATM" && name != "DELE")
                    {
                        objValue = t.GetProperty(name).GetValue(obj, null);
                        if (objValue != null)
                            strValue = objValue.ToString();
                        else
                            strValue = "";

                        hst.Add(name, strValue);
                    }
                }

            return hst;
        }

        public static LogBO CreateLog(object obj, string FieldID, TacVu tacVu, string table, int objectID)
        {
            LogBO logBO = null;

            string tenTacVu = (tacVu == TacVu.Them ? "Thêm" : tacVu == TacVu.Sua ? "Sửa" : "Xóa") + " " + table;

            Type t = obj.GetType();
            MemberInfo[] mi = t.GetMembers();

            int i = 0;
            int length = mi.Length;

            string name = "";
            object objValue = null;
            string strNewValue = "";
            string strValue = "";

            switch (tacVu)
            {
                case TacVu.Them:
                case TacVu.Xoa:
                    for (i = 0; i < length; i++)
                        if (mi[i].MemberType == MemberTypes.Property)
                        {
                            name = mi[i].Name;
                            if (table == "NhanVien" && name == "Anh")
                            {
                            }
                            else
                                if (Log_ValidColumn(name))
                                {
                                    objValue = t.GetProperty(name).GetValue(obj, null);
                                    if (objValue != null)
                                        strValue = objValue.ToString();
                                    else
                                        strValue = " ";

                                    strNewValue += strValue + "|";
                                }
                        }

                    logBO = LogBOCollection.NewLogBO();
                    logBO.TacVu = tenTacVu;
                    logBO.ObjectID = objectID;
                    logBO.NewValue = strNewValue;
                    break;
                case TacVu.Sua:
                    Hashtable hst = (Hashtable)t.GetProperty("HstOldValue").GetValue(obj, null);
                    for (i = 0; i < length; i++)
                        if (mi[i].MemberType == MemberTypes.Property)
                        {
                            name = mi[i].Name;
                            if (Log_ValidColumn(name) && name != FieldID)
                            {
                                objValue = t.GetProperty(name).GetValue(obj, null);
                                if (objValue != null)
                                    strValue = objValue.ToString();
                                else
                                    strValue = "";

                                if ((string)hst[name] != strValue)
                                {
                                    if ((table == "NhanVien" && name == "Anh") || (table == "ThietDat" && name == "NoiDungI"))
                                        strNewValue += "Thay ảnh|";
                                    else
                                        strNewValue += name + ":[" + (string)hst[name] + "] -> [" + strValue + "]|";
                                }
                            }
                        }

                    if (strNewValue != "")
                    {
                        logBO = LogBOCollection.NewLogBO();
                        logBO.TacVu = tenTacVu;
                        logBO.ObjectID = objectID;
                        logBO.NewValue = strNewValue;
                    }
                    break;
            }

            if (logBO == null)
            {
                logBO = LogBOCollection.NewLogBO();
                logBO.TacVu = null;
            }

            return logBO;
        }

        public static string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }

        public static ModuleItem GetModuleItem(int ModuleID)
        {
            int length = Session.lstModuleItem.Count;
            for (int i = 0; i < length; i++)
                if (Session.lstModuleItem[i].ModuleID == ModuleID)
                    return Session.lstModuleItem[i];

            return null;
        }

        public static string[] GetDanhMuc(LoaiDanhMuc loaiDanhMuc)
        {
            switch (loaiDanhMuc)
            {
                case LoaiDanhMuc.DanToc:
                    return new string[] { "DanToc", "Dân tộc" };
                case LoaiDanhMuc.TonGiao:
                    return new string[] { "TonGiao", "Tôn giáo" };
                case LoaiDanhMuc.QuocTich:
                    return new string[] { "QuocTich", "Quốc tịch" };
                case LoaiDanhMuc.TrinhDoHocVan:
                    return new string[] { "TrinhDoHocVan", "Trình độ học vấn" };
                case LoaiDanhMuc.TrinhDoNgoaiNgu:
                    return new string[] { "TrinhDoNgoaiNgu", "Trình độ ngoại ngữ" };
                case LoaiDanhMuc.TrinhDoTinHoc:
                    return new string[] { "TrinhDoTinHoc", "Trình độ tin học" };
                case LoaiDanhMuc.BangCap:
                    return new string[] { "BangCap", "Bằng cấp" };
                case LoaiDanhMuc.ChuyenMon:
                    return new string[] { "ChuyenMon", "Chuyên môn" };
                case LoaiDanhMuc.LoaiTaiKhoan:
                    return new string[] { "LoaiTaiKhoan", "Loại tài khoản" };
                case LoaiDanhMuc.LoaiHopDongLaoDong:
                    return new string[] { "LoaiHopDongLaoDong", "Loại hợp đồng lao động" };
                case LoaiDanhMuc.NhomKhachHang:
                    return new string[] { "NhomKhachHang", "Nhóm Khách hàng" };
                case LoaiDanhMuc.PhuongThucThanhToan:
                    return new string[] { "PhuongThucThanhToan", "Nhóm Khách hàng" };
                case LoaiDanhMuc.DanhMucKho:
                    return new string[] { "DanhMucKho", "Danh mục Kho" };
                case LoaiDanhMuc.HangSanXuat:
                    return new string[] { "HangSanXuat", "Hãng Sản xuất" };
                case LoaiDanhMuc.NuocSanXuat:
                    return new string[] { "NuocSanXuat", "Nước Sản xuất" };
                case LoaiDanhMuc.LoaiChiPhi:
                    return new string[] { "LoaiChiPhi", "Loại Chi phí" };
                case LoaiDanhMuc.DonViTinh:
                    return new string[] { "DonViTinh", "Đơn vị tính" };
                case LoaiDanhMuc.QuyenHan:
                    return new string[] { "QuyenHan", "Quyền hạn" };
                default:
                    return new string[] { "", "" };
            }
        }

        public static string GetLoaiDanhMuc(LoaiDanhMuc loaiDanhMuc)
        {
            return GetDanhMuc(loaiDanhMuc)[0];
        }

        public static string RebuiltHoTen(string s)
        {
            if (string.IsNullOrEmpty(s))
                return s;
            else
            {
                s = s.Trim();
                while (s.IndexOf("  ") >= 0)
                    s = s.Replace("  ", " ");

                string[] arrS = s.Split(' ');
                s = "";
                int i = 0;
                for (i = 0; i < arrS.Length; i++)
                {
                    if (!string.IsNullOrEmpty(arrS[i]))
                    {
                        s += (s == "" ? "" : " ");
                        if (arrS[i].Length == 1)
                            s += arrS[i].ToUpper();
                        else
                            s += arrS[i].Substring(0, 1).ToUpper() + arrS[i].Substring(1).ToLower();
                    }
                }
            }

            return s;
        }

        public static string GetFilenameOnly(string s)
        {
            if (string.IsNullOrEmpty(s))
                return "";
            else
            {
                int i = s.LastIndexOf("\\");
                s = s.Substring(i + 1);
                return s;
            }
        }

        public static string UpperFirstCharacter(string s)
        {
            s = s.ToLower().Trim();
            string s1 = s.Substring(0, 1).ToUpper();
            s = s.Remove(0, 1);
            s = s.Insert(0, s1);
            return s;
        }

        public static int GetIntFromDT(DateTime? dt)
        {
            if (dt == null)
                return 0;
            else
                return dt.Value.Year * 10000 + dt.Value.Month * 100 + dt.Value.Day;
        }
        #endregion other

        #region Database
        public static void AttactDB(string mdfFile, string dbname)
        {
            string DBConnectionStr = "Data Source=" + Session.SqlDataSource + ";Initial Catalog=master;Trusted_Connection=true;";

            try
            {
                using (SqlConnection cnn = new SqlConnection(DBConnectionStr))
                {
                    cnn.Open();
                    string scmd = "sp_attach_single_file_db @dbname = '" + dbname + "', @physname = N'" + mdfFile + "'";
                    SqlCommand cmd = new SqlCommand(scmd, cnn);
                    cmd.ExecuteNonQuery();

                    scmd = "if not exists (select name from master.sys.databases sd where name = N'" + dbname + "' and SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() ) EXEC [" + dbname + "].dbo.sp_changedbowner @loginame=N'" + Session.SqlUserID + "', @map=false";
                    cmd.CommandText = scmd;
                    cmd.ExecuteNonQuery();

                    cnn.Close();
                    cnn.Dispose();
                }
            }
            catch { throw; }
        }

        public static void AttactDB(string sourceFile, string descPath, string dbname)
        {
            string DBConnectionStr = "Data Source=" + Session.SqlDataSource + ";Initial Catalog=master;Trusted_Connection=true;";

            try
            {
                File.Copy(sourceFile, descPath + dbname + ".mdf", true);

                using (SqlConnection cnn = new SqlConnection(DBConnectionStr))
                {
                    cnn.Open();
                    string scmd = "sp_attach_single_file_db @dbname = '" + dbname + "', @physname = N'" + descPath + dbname + ".mdf'";
                    SqlCommand cmd = new SqlCommand(scmd, cnn);
                    cmd.ExecuteNonQuery();

                    scmd = "if not exists (select name from master.sys.databases sd where name = N'" + dbname + "' and SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() ) EXEC [" + dbname + "].dbo.sp_changedbowner @loginame=N'" + Session.SqlUserID + "', @map=false";
                    cmd.CommandText = scmd;
                    cmd.ExecuteNonQuery();

                    cnn.Close();
                    cnn.Dispose();
                }
            }
            catch { throw; }
        }

        public static void DetactDB(string dbname)
        {
            string DBConnectionStr = "Data Source=" + Session.SqlDataSource + ";Initial Catalog=master;Trusted_Connection=true;";

            try
            {
                using (SqlConnection cnn = new SqlConnection(DBConnectionStr))
                {
                    cnn.Open();
                    string scmd = "DECLARE @SQL varchar(max)\r\nSET @SQL = ''\r\nSELECT @SQL = @SQL + 'Kill ' + Convert(varchar, SPId) + ';'\r\nFROM MASTER..SysProcesses\r\nWHERE DBId = DB_ID(N'" + dbname + "') AND SPId <> @@SPId\r\nEXEC(@SQL)";

                    using (SqlCommand cmd = new SqlCommand(scmd, cnn))
                    {
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = "EXEC master.dbo.sp_detach_db @dbname = N'" + dbname + "', @keepfulltextindexfile=N'true'";
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                    }

                    cnn.Close();
                    cnn.Dispose();
                }
            }
            catch { throw; }
        }

        public static void CreateSqlUserID(string username, string password)
        {
            string DBConnectionStr = "Data Source=" + Session.SqlDataSource + ";Initial Catalog=master;Trusted_Connection=true;";

            try
            {
                using (SqlConnection cnnGetAllDB = new SqlConnection(DBConnectionStr))
                {
                    cnnGetAllDB.Open();

                    bool hasDBUSR = false;
                    using (SqlCommand cmdGetAllLogins = new SqlCommand("SELECT * FROM syslogins WHERE name=N'" + username + "'", cnnGetAllDB))
                    {
                        using (SqlDataReader reader = cmdGetAllLogins.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                string loginsName = (string)reader["name"];
                                if (loginsName.ToUpper() == username.ToUpper())
                                    hasDBUSR = true;
                            }

                            reader.Close();
                            reader.Dispose();
                        }

                        cmdGetAllLogins.Dispose();
                    }

                    if (hasDBUSR == false)
                    {
                        using (SqlCommand cmdAddDBUSR = new SqlCommand("CREATE LOGIN [" + username + "] WITH PASSWORD=N'" + password + "', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF", cnnGetAllDB))
                        {
                            cmdAddDBUSR.ExecuteNonQuery();
                            cmdAddDBUSR.Dispose();
                        }

                        using (SqlCommand cmdSetAdminRole = new SqlCommand("EXEC sys.sp_addsrvrolemember @loginame = N'" + username + "', @rolename = N'sysadmin'", cnnGetAllDB))
                        {
                            cmdSetAdminRole.ExecuteNonQuery();
                            cmdSetAdminRole.Dispose();
                        }
                    }

                    cnnGetAllDB.Close();
                    cnnGetAllDB.Dispose();
                }
            }
            catch { throw; }
        }

        public static bool CheckDB(string DBname)
        {
            string DBConnectionStr = "Data Source=" + Session.SqlDataSource + ";Initial Catalog=master;Trusted_Connection=true;";
            bool isExist = false;

            try
            {
                using (SqlConnection cnnGetAllDB = new SqlConnection(DBConnectionStr))
                {
                    cnnGetAllDB.Open();

                    using (SqlCommand cmdGetAllDB = new SqlCommand("SELECT name AS DBName FROM sys.databases", cnnGetAllDB))
                    {
                        using (SqlDataReader reader = cmdGetAllDB.ExecuteReader())
                        {
                            string name = "";
                            DBname = DBname.ToUpper();

                            while (reader.Read())
                            {
                                name = (string)reader[0];
                                if (name.ToUpper() == DBname)
                                {
                                    isExist = true;
                                    break;
                                }
                            }

                            reader.Close();
                            reader.Dispose();
                        }

                        cmdGetAllDB.Dispose();
                    }

                    cnnGetAllDB.Close();
                    cnnGetAllDB.Dispose();
                }
            }
            catch { throw; }

            return isExist;
        }

        public static object[] GetInfoDB(string dbname, bool getLockFile)
        {
            //return: real path; size (bytes); log_file
            string scmd = "SELECT DB_NAME(mf.database_id) AS DatabaseName,mf.physical_name AS physical_name,size_on_disk_bytes FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS divfs JOIN sys.master_files AS mf ON mf.database_id = divfs.database_id AND mf.file_id = divfs.file_id AND DB_NAME(mf.database_id)=N'" + dbname + "'";

            if (getLockFile == false)
                scmd += " AND mf.physical_name LIKE '%.mdf'";

            scmd += " ORDER BY DatabaseName";
            object[] result = new object[3];

            string DBConnectionStr = "Data Source=" + Session.SqlDataSource + ";Initial Catalog=master;Trusted_Connection=true;";

            try
            {
                using (SqlConnection cnn = new SqlConnection(DBConnectionStr))
                {
                    cnn.Open();

                    using (SqlCommand cmd = new SqlCommand(scmd, cnn))
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            string physical_name = "";

                            while (reader.Read())
                            {
                                physical_name = (string)reader["physical_name"];

                                if (physical_name.ToLower().EndsWith(".mdf"))
                                {
                                    result[0] = physical_name;
                                    result[1] = CalSizeOnBytes(reader["size_on_disk_bytes"]);
                                }
                                else
                                    if (physical_name.ToLower().EndsWith(".ldf"))
                                        result[2] = physical_name;
                            }

                            reader.Close();
                            reader.Dispose();
                        }

                        cmd.Dispose();
                    }

                    cnn.Close();
                    cnn.Dispose();
                }
            }
            catch { throw; }

            return result;
        }

        private static string CalSizeOnBytes(object size)
        {
            string[] arrTrailer = new string[] { "byte", "KB", "MB", "GB", "TB" };
            long iSize = Convert.ToInt64(size);
            int i = 0;
            long valueDIV = 1;

            while (iSize / valueDIV >= 1024)
            {
                valueDIV *= 1024;
                i++;
                if (i == 4)
                    break;
            }

            if (iSize / valueDIV < 1 && i > 0)
            {
                valueDIV /= 2024;
                i--;
            }

            long mod = iSize % valueDIV;

            return (mod == 0L ? (iSize / valueDIV).ToString() : Math.Round((decimal)(iSize / (1.0 * valueDIV)), 1, MidpointRounding.AwayFromZero).ToString()) + " " + arrTrailer[i];
        }
        #endregion Database

        #region Doi tien tu so sang chu
        public static String ConvertMoney2Str(decimal? number)
        {
            if (number == null)
                return "";

            string s = number.Value.ToString("#");
            string[] so = new string[] { "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín" };
            string[] hang = new string[] { "", "nghìn", "triệu", "tỉ" };
            int i, j, donvi, chuc, tram;
            string str = " ";
            bool booAm = false;
            decimal decS = 0;

            try
            {
                decS = Convert.ToDecimal(s.ToString());
            }
            catch
            {
            }
            if (decS < 0)
            {
                decS = -decS;
                s = decS.ToString();
                booAm = true;
            }
            i = s.Length;
            if (i == 0)
                str = so[0] + str;
            else
            {
                j = 0;
                while (i > 0)
                {
                    donvi = Convert.ToInt32(s.Substring(i - 1, 1));
                    i--;
                    if (i > 0)
                        chuc = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        chuc = -1;
                    i--;
                    if (i > 0)
                        tram = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        tram = -1;
                    i--;
                    if ((donvi > 0) || (chuc > 0) || (tram > 0) || (j == 3))
                        str = hang[j] + str;
                    j++;
                    if (j > 3) j = 1;
                    if ((donvi == 1) && (chuc > 1))
                        str = " mốt " + str;
                    else
                    {
                        if ((donvi == 5) && (chuc > 0))
                            str = " lăm " + str;
                        else if (donvi > 0)
                            str = so[donvi] + " " + str;
                    }
                    if (chuc < 0)
                        break;
                    else
                    {
                        if ((chuc == 0) && (donvi > 0)) str = "lẻ " + str;
                        if (chuc == 1) str = " mười " + str;
                        if (chuc > 1) str = so[chuc] + " mươi " + str;
                    }
                    if (tram < 0) break;
                    else
                    {
                        if ((tram > 0) || (chuc > 0) || (donvi > 0)) str = so[tram] + " trăm " + str;
                    }
                    str = " " + str;
                }
            }

            if (booAm) str = "Âm " + str;

            str = str.Replace("  ", " ");
            return str;//+ "đồng chẳn";
        }

        public static String ConvertMoney2Str(string number)
        {
            string s = number;
            string[] so = new string[] { "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín" };
            string[] hang = new string[] { "", "nghìn", "triệu", "tỉ" };
            int i, j, donvi, chuc, tram;
            string str = " ";
            bool booAm = false;
            decimal decS = 0;
            //Tung addnew
            try
            {
                decS = Convert.ToDecimal(s.ToString());
            }
            catch
            {
            }
            if (decS < 0)
            {
                decS = -decS;
                s = decS.ToString();
                booAm = true;
            }
            i = s.Length;
            if (i == 0)
                str = so[0] + str;
            else
            {
                j = 0;
                while (i > 0)
                {
                    donvi = Convert.ToInt32(s.Substring(i - 1, 1));
                    i--;
                    if (i > 0)
                        chuc = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        chuc = -1;
                    i--;
                    if (i > 0)
                        tram = Convert.ToInt32(s.Substring(i - 1, 1));
                    else
                        tram = -1;
                    i--;
                    if ((donvi > 0) || (chuc > 0) || (tram > 0) || (j == 3))
                        str = hang[j] + str;
                    j++;
                    if (j > 3) j = 1;
                    if ((donvi == 1) && (chuc > 1))
                        str = " mốt " + str;
                    else
                    {
                        if ((donvi == 5) && (chuc > 0))
                            str = " lăm " + str;
                        else if (donvi > 0)
                            str = so[donvi] + " " + str;
                    }
                    if (chuc < 0)
                        break;
                    else
                    {
                        if ((chuc == 0) && (donvi > 0)) str = "lẻ " + str;
                        if (chuc == 1) str = " mười " + str;
                        if (chuc > 1) str = so[chuc] + " mươi " + str;
                    }
                    if (tram < 0) break;
                    else
                    {
                        if ((tram > 0) || (chuc > 0) || (donvi > 0)) str = so[tram] + " trăm " + str;
                    }
                    str = " " + str;
                }
            }

            if (booAm) str = "Âm " + str;

            str = str.Replace("  ", " ");
            return str;//+ "đồng chẳn";
        }

        public static String ConvertMoney2Str(double? number)
        {
            if (number == null)
                return "";

            string str = "";
            string sothuc = number.ToString();
            string sohangchuc = "";
            string sohangphey = "";

            int indexdauphey = sothuc.IndexOf(',');
            int length = sothuc.Length;
            if (indexdauphey > -1)
            {
                sohangchuc = sothuc.Substring(0, indexdauphey);
                sohangphey = sothuc.Substring(indexdauphey + 1, length - indexdauphey - 1);
                str = ConvertMoney2Str(Convert.ToDecimal(sohangchuc)) + " phẩy " + ConvertMoney2Str(sohangphey) + "đồng";
            }
            else
            {
                str = ConvertMoney2Str(Convert.ToDecimal(sothuc)) + "đồng";
            }
            str = str.Trim();
            str = str.Substring(0, 1).ToUpper() + str.Remove(0, 1);

            str = str.Replace("  ", " ");
            return str;
        }
        #endregion Doi tien tu so sang chu

        #region Lay ngay gio he thong
        public static DateTime GetDateTimeFromServer()
        {
            DateTime currentDateTime = DateTime.Now;

            try
            {
                using (SqlConnection cnn = new SqlConnection(Session.DBConnectionString))
                {
                    cnn.Open();

                    using (SqlCommand cmd = new SqlCommand("SELECT GETDATE() FROM ThietDat", cnn))
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                                currentDateTime = (DateTime)reader[0];

                            reader.Close();
                            reader.Dispose();
                        }

                        cmd.Dispose();
                    }

                    cnn.Close();
                    cnn.Dispose();
                }
            }
            catch { throw; }
            return currentDateTime;
        }

        #endregion
    }
}
